// https://leetcode.cn/problems/lru-cache/?envType=study-plan-v2&envId=top-interview-150

struct Node {
    int key;
    int value;
    Node* prev;
    Node* next;

    Node() {
        value = 0;
        prev = nullptr;
        next = nullptr;
    }

    Node(int k, int val) {
        key = k;
        value = val;
        prev = nullptr;
        next = nullptr;
    }
};

class LRUCache {
private:
    int capacity;
    int size;
    Node* head;
    Node* tail;
    unordered_map<int, Node*> mp;
public:
    LRUCache(int capacity) {
        this->size = 0;
        this->capacity = capacity;
        head = new Node();
        tail = new Node();
        head->next = tail;
        tail->prev = head;
    }
    
    int get(int key) {
        if (mp.count(key)) {
            moveToTail(mp[key]);
            return mp[key]->value;
        }

        return -1;
    }
    
    void put(int key, int value) {
        if (!mp.count(key)) {
            Node* newNode = new Node(key, value);
            mp[key] = newNode;
            addToTail(newNode);
            size++;

            if (size > capacity) {
                Node* cur = removeHead();
                mp.erase(cur->key);
                delete cur;
                size--;
            }
        } else {
            Node* cur = mp[key];
            cur->value = value;
            moveToTail(cur);
        }
    }

    void moveToTail(Node* node) {
        remove(node);
        addToTail(node);
    }

    void remove(Node* node) {
        node->prev->next = node->next;
        node->next->prev = node->prev;
    }

    void addToTail(Node* node) {
        node->prev = tail->prev;
        node->next = tail;
        tail->prev->next = node;
        tail->prev = node;
    }

    Node* removeHead() {
        Node* cur = head->next;
        head->next = cur->next;
        cur->next->prev = head;
        return cur;
    }
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */